﻿using BaseBll;
using BaseWebApi.Common;
using BaseWebApi.Models;
using Common;
using Models;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;

namespace BaseWebApi.QuartzJob
{
    public sealed class AssetKeepWarnJob : IJobModel
    {
        /// <summary>
        /// 触发时间
        /// </summary>
        public string JobTime { get { return "0 0 0 * * ?"; } set { JobTime = value; } }
        /// <summary>
        /// 任务名称
        /// </summary>
        public string JobName { get { return "AssetKeepWarn"; } set { JobName = value; } }

        /// <summary>
        /// 任务具体逻辑
        /// </summary>
        /// <param name="context"></param>
        public void Execute(IJobExecutionContext context)
        {
            var playload = new JWTPlayloadInfo { LoginIP = "127.0.0.1", UserName = "主机" };
            try
            {
                List<AssetKeepWarn> resultList = new List<AssetKeepWarn>();
                // 获取需要提醒的资产
                List<AssetHead> assetList = AssetInvBll.Instance.GetKeepTimeWarnAsset();
                // 获取提醒数据
                resultList = GetWarnList(assetList);

                if (resultList.Count > 0)
                {
                    // 添加到资产维护提醒表中
                    int res = AssetKeepWarnBll.Instance.AddList(resultList);
                    if (res > 0)
                    {
                        LogHelper.LogAction(playload, Constant.SysModule.QuartzJob, Constant.ActionEnum.Add, $"定时任务-生成资产维护提醒(已成功生成{res}条数据)");
                    }
                    else
                    {
                        LogHelper.LogWarn(playload, Constant.SysModule.QuartzJob, Constant.ActionEnum.Add, "定时任务-生成资产维护提醒(生成失败)");
                    }
                }

            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.QuartzJob, Constant.ActionEnum.Add, "定时任务-生成资产维护提醒（异常）");
            }

        }

        /// <summary>
        /// 获取提醒数据（去掉已存在数据）
        /// </summary>
        /// <param name="assetList"></param>
        /// <returns></returns>
        public List<AssetKeepWarn> GetWarnList(List<AssetHead> assetList)
        {
            List<AssetKeepWarn> resultList = new List<AssetKeepWarn>();

            if (assetList != null && assetList.Any())
            {
                // Collect all unique combinations of AssetNo, MaintainTimeStart, and MaintainTimeEnd
                var uniqueCriteria = assetList
                    .Select(item => new { item.AssetNo, item.MaintainTimeStart, item.MaintainTimeEnd })
                    .Distinct();

                // Construct the WHERE clause for batch query
                string strWhere = " and (" + string.Join(" OR ", uniqueCriteria.Select(c =>
                    $"(AssetNo='{c.AssetNo}' AND MaintainTimeStart='{c.MaintainTimeStart}' AND MaintainTimeEnd='{c.MaintainTimeEnd}')")) + ")";

                // Execute the batch query
                var existingAssets = AssetKeepWarnBll.Instance.GetList(strWhere);

                foreach (var item in assetList)
                {
                    // Check if the current item exists in the batch query result
                    if (!existingAssets.Any(a => a.AssetNo == item.AssetNo && a.MaintainTimeStart == item.MaintainTimeStart && a.MaintainTimeEnd == item.MaintainTimeEnd))
                    {
                        resultList.Add(new AssetKeepWarn
                        {
                            AssetNo = item.AssetNo,
                            AssetName = item.AssetName,
                            Specs = item.Specs,
                            MaintainTimeStart = item.MaintainTimeStart,
                            MaintainTimeEnd = item.MaintainTimeEnd
                        });
                    }
                }
            }

            return resultList;
        }
    }
}
